package com.work.daily.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Shengkang.Mo
 * @create 2021-02-07 15:14
 * @description 两数之和
 */
public class TwoSumDemo {

    public static void main(String[] args) {
        int[] source = {2, 5, 7, 9, 11};
        int target = 12;

        long start = System.currentTimeMillis();
        int[] index = hashSolve(target, source);
        System.out.println("time(s) = " + (System.currentTimeMillis() - start) / 1000);

        if (null != index) {
            for (int i = 0; i < index.length; i++) {
                System.out.println(index[i]);
            }
        }
    }

    /**
     * 暴力破解
     *
     * @param target 目标数
     * @param source 源数据
     * @return 索引数组
     */
    public static int[] forceSolve(int target, int[] source) {
        for (int i = 0; i < source.length; i++) {
            for (int j = 1; j < source.length; j++) {
                if (target - source[i] == source[j]) {
                    return new int[]{i, j};
                }
            }
        }
        return null;
    }

    /**
     * 哈希破解
     *
     * @param target 目标数
     * @param source 源数据
     * @return 索引数组
     */
    public static int[] hashSolve(int target, int[] source) {
        Map<Integer, Integer> map = new HashMap<>(source.length);
        for (int i = 0; i < source.length; i++) {
            int temp = target - source[i];
            if (map.containsKey(temp) && null != map.get(temp)) {
                return new int[]{map.get(temp), i};
            }
            map.put(source[i], i);
        }
        return null;
    }
}
